package com.qiyun.framework.adapter;

import android.content.Context;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.qiyun.framework.helper.BitmapHelper;


/**
 * Created by mac on 16/3/22.
 */
public class ViewHolder {
    private final SparseArray<View> mViews;
    private View mConvertView;

    private ViewHolder(Context context, ViewGroup parent, int layoutId,
                       int position) {
        this.mViews = new SparseArray<View>();
        mConvertView = LayoutInflater.from(context).inflate(layoutId, parent, false);
        //setTag
        mConvertView.setTag(this);


    }

    /**
     * 拿到一个ViewHolder对象
     *
     * @param context
     * @param convertView
     * @param parent
     * @param layoutId
     * @param position
     * @return
     */
    public static ViewHolder get(Context context, View convertView,
                                 ViewGroup parent, int layoutId, int position) {

        if (convertView == null) {
            return new ViewHolder(context, parent, layoutId, position);
        }
        return (ViewHolder) convertView.getTag();
    }


    /**
     * 通过控件的Id获取对于的控件，如果没有则加入views
     *
     * @param viewId
     * @return
     */
    public <T extends View> T getView(int viewId) {

        View view = mViews.get(viewId);
        if (view == null) {
            view = mConvertView.findViewById(viewId);
            mViews.put(viewId, view);
        }
        return (T) view;
    }

    public View getConvertView() {
        return mConvertView;
    }


    /**
     * 对textView简单控件进行封装
     */
    public void setText(int layoutId,String str){
        try {
            ((TextView)getView(layoutId)).setText(str);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 对ImageView简单控件进行封装
     */
    public void setImage(int layoutId,int imgRes){
        try {
            ((ImageView)getView(layoutId)).setImageResource(imgRes);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     *  对ImageView简单控件进行封装网络获取
     * @param layoutId
     * @param imgUrl image的网络url
     */
    public void setImage(int layoutId,String imgUrl){
        try {
            BitmapHelper.getBitmapUtils().bind(((ImageView) getView(layoutId)),imgUrl);
        }catch (Exception e){
            e.printStackTrace();
        }
    }


}
